package com.sntk.organauthomanager.infrastructure.autho;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sntk.organauthomanager.application.dto.HisOperatorInfo;
import com.sntk.organauthomanager.application.dto.OperatorInfo;
import com.sntk.organauthomanager.application.service.LoginApplicationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @ClassName: AuthenticationInterceptor
 * @author: wgchao
 * @createTime: 2020/8/5 10:37 AM
 * @Description: 身份验证拦截器
 */
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    private LoginApplicationService loginApplicationService;

    private static final Logger logger = LoggerFactory.getLogger(AuthenticationInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        String token = httpServletRequest.getHeader("logininfo");// 从 http 请求头中取出 user
        // 如果不是映射到方法直接通过
        if(!(object instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod=(HandlerMethod)object;
        Method method=handlerMethod.getMethod();
        //检查是否有passtoken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }else{
            //其他的接口需要token检校
//            if(StringUtils.isEmpty(token)){
//                throw new RuntimeException("用户未登录，请登录后操作！");
//            }
//            OperatorInfo user = loginApplicationService.autho(token);
            HisOperatorInfo user = JSON.parseObject(token, HisOperatorInfo.class);
            //加入session
            httpServletRequest.getSession().setAttribute("loginUser", user);
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
